package com.example.demofx.master;

import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Modality;
import javafx.stage.Stage;

import java.util.ArrayList;
import java.util.List;

import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;

public class GroupCreate extends Application {

    private GroupManager groupManager;
    private ContactManager contactManager; // 新增：用于获取系统联系人
    private ListView<String> allContactsList;
    private ListView<String> selectedContactsList;
    private GroupCreationListener listener;

    public GroupCreate(GroupManager groupManager, ContactManager contactManager) {
        this.groupManager = groupManager;
        this.contactManager = contactManager;
    }

    // 组创建成功的回调接口
    public interface GroupCreationListener {
        void onGroupCreated();
    }

    // 设置组创建成功的监听器
    // @return 无返回值，注册回调接口实现
    public void setGroupCreationListener(GroupCreationListener listener) {
        this.listener = listener;
    }

    // 启动 JavaFX 应用程序
    @Override
    public void start(Stage primaryStage) {
        showCreateGroupDialog(primaryStage);
    }

    // 显示创建组的对话框
    private void showCreateGroupDialog(Stage parentStage) {
        Stage dialog = new Stage();
        dialog.initModality(Modality.APPLICATION_MODAL);
        dialog.initOwner(parentStage);
        dialog.setTitle("新建组");

        // 顶部：组名输入框
        TextField groupNameField = new TextField();
        groupNameField.setPromptText("请输入组名");

        // 初始化所有联系人列表（从系统加载真实数据）
        allContactsList = new ListView<>();
        loadSystemContacts(); // 加载系统联系人

        // 搜索框
        TextField searchField = new TextField();
        searchField.setPromptText("查找联系人...");
        searchField.textProperty().addListener((observable, oldValue, newValue) -> filterContacts(newValue));

        VBox leftBox = new VBox(5, new Label("所有联系人"), searchField, allContactsList);
        leftBox.setPrefWidth(250);
        leftBox.setMaxHeight(300);

        // 初始化已选联系人列表
        selectedContactsList = new ListView<>();
        selectedContactsList.setPlaceholder(new Label(""));

        VBox rightBox = new VBox(10, new Label("已选联系人"), selectedContactsList);
        rightBox.setPrefWidth(250);
        rightBox.setMaxHeight(300);

        // 中间：按钮区域（修改为文本按钮）
        Button addButton = new Button(">>移入");
        addButton.setStyle("-fx-font-size: 14px; -fx-base: #FFFBDE; -fx-padding: 5 15;");
        addButton.setOnAction(e -> moveSelectedItems(allContactsList, selectedContactsList));

        Button removeButton = new Button("<<移除");
        removeButton.setStyle("-fx-font-size: 14px; -fx-base: #90D1CA; -fx-padding: 5 15;");
        removeButton.setOnAction(e -> moveSelectedItems(selectedContactsList, allContactsList));

        VBox arrowBox = new VBox(10, addButton, removeButton);
        arrowBox.setPrefWidth(80);
        arrowBox.setStyle("-fx-alignment: center;");

        HBox centerBox = new HBox(10, leftBox, arrowBox, rightBox);
        centerBox.setStyle("-fx-padding: 10;");

        // 底部按钮
        Button saveBtn = new Button("保存");
        saveBtn.setOnAction(e -> {
            String groupName = groupNameField.getText().trim();
            if (!groupName.isEmpty()) {
                if (groupManager.isGroupNameExists(groupName)) {
                    // 显示警告对话框（组名已存在）
                    Alert alert = new Alert(Alert.AlertType.WARNING, "组名已存在", ButtonType.OK);
                    alert.showAndWait();
                } else {
                    // 创建新的分组对象
                    Group newGroup = new Group(groupName);
                    // 将新分组保存到数据库
                    if (groupManager.addGroup(newGroup)) {
                        // 遍历已选择的联系人列表
                        for (String contactName : selectedContactsList.getItems()) {
                            Contact contact = findContactByName(contactName);
                            if (contact != null) {
                                // 将新分组添加到联系人的分组列表（内存中）
                                contact.getGroups().add(newGroup);
                                // 更新数据库：将联系人添加到新分组
                                groupManager.addContactToGroup(contact, newGroup);
                            }
                        }
                        // 通知主应用程序刷新UI（通过回调接口）
                        if (listener != null) {
                            listener.onGroupCreated();
                        }
                        dialog.close();
                    }
                }
            } else {
                showAlert(dialog, "提示", "请输入组名！");
            }
        });

        Button cancelBtn = new Button("取消");
        cancelBtn.setOnAction(e -> dialog.close());

        HBox buttonBox = new HBox(10, saveBtn, cancelBtn);
        buttonBox.setStyle("-fx-alignment: center-right; -fx-padding: 10;");

        // 布局整合
        VBox layout = new VBox(10, groupNameField, centerBox, buttonBox);
        layout.setStyle("-fx-padding: 10;");

        dialog.setScene(new Scene(layout, 650, 400));
        dialog.show();
    }

    // 从系统加载所有联系人
    private void loadSystemContacts() {
        if (contactManager != null) {
            ObservableList<String> contactNames = FXCollections.observableArrayList();
            for (Contact contact : contactManager.getAllContacts()) {
                contactNames.add(contact.getName());
            }
            allContactsList.setItems(contactNames);
        } else {
            // 如果 contactManager 为空，使用示例数据
            allContactsList.getItems().addAll(generateSampleContacts());
        }
    }

    // 根据名称查找联系人
    private Contact findContactByName(String name) {
        if (contactManager != null) {
            for (Contact contact : contactManager.getAllContacts()) {
                if (contact.getName().equals(name)) {
                    return contact;
                }
            }
        }
        return null;
    }

    // 过滤联系人列表
    private void filterContacts(String keyword) {
        if (contactManager != null) {
            ObservableList<String> filteredNames = FXCollections.observableArrayList();
            for (Contact contact : contactManager.getAllContacts()) {
                if (contact.getName().toLowerCase().contains(keyword.toLowerCase())) {
                    filteredNames.add(contact.getName());
                }
            }
            allContactsList.setItems(filteredNames);
        }
    }

    // 在两个列表视图之间移动选中项
    private void moveSelectedItems(ListView<String> fromList, ListView<String> toList) {
        ObservableList<String> selectedItems = FXCollections.observableArrayList(fromList.getSelectionModel().getSelectedItems());
        toList.getItems().addAll(selectedItems);
        fromList.getItems().removeAll(selectedItems);
        fromList.getSelectionModel().clearSelection();
    }

    // 生成示例联系人数据（仅在 contactManager 为空时使用（测试用））
    private List<String> generateSampleContacts() {
        List<String> contacts = new ArrayList<>();
        for (int i = 1; i <= 20; i++) {
            contacts.add("联系人" + i);
        }
        return contacts;
    }

    // 显示提示框
    private void showAlert(Stage owner, String title, String message) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.initOwner(owner);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }

    public static void main(String[] args) {
        launch(args);
    }
}